import java.io.FileNotFoundException;
import java.io.IOException;


public class BruteForce {
	static double confidence;
	
	public static double CalcSuccess(String PlainText, WordDictionary wd){
		int counter=0;
		PlainText = PlainText.toLowerCase();
		String[] words = PlainText.split(" ");
		
		for (int i=0; i<words.length; i++)
			if (wd.WordExists(words[i]))
				counter++;
		
		return ((double)counter)/((double)words.length);
	}
	
	public static LargeKey Crack(LargeKey key, byte[] cipher, WordDictionary wd, int BlockSize) throws FileNotFoundException, IOException  {
		double max=0, res;
		LargeKey best=key, temp;
		int i, j;
		String pt="";
		Stock st = new Stock();
		
		if (key.isFullyMapped()){
			//pt = st.improvedTransform(cipher, key, BlockSize);
			//res = CalcSuccess(pt, wd);
			//System.out.println(res);
			return key;
		}
		
		for (i=0; i< 52; i++){
			if(key.Plain2Cipher[i]==0){
				for (j=0; j<52; j++){
					if (key.Cipher2Plain[j]==0){
						temp = new LargeKey(key);
						temp.SetValue(temp.TranslateIndexToChar(i), temp.TranslateIndexToChar(j), "plain");
						temp.SetValue(temp.TranslateIndexToChar(j), temp.TranslateIndexToChar(i), "cipher");
						temp = Crack(temp, cipher, wd, BlockSize);
						
						pt = st.improvedTransform(cipher, temp, BlockSize);
						res = CalcSuccess(pt, wd);
						
						if( res > max){
							max = res;
							best = temp;
						}
					}
				}
				break;
			}
		}
		
		key = best;
		confidence = max;
		return best;
	}
}
